package com.cg.springSecurity.security;


import com.cg.springSecurity.pojo.User;
import com.google.gson.Gson;
import com.cg.springSecurity.base.ResultInfo;
import com.cg.springSecurity.utils.JwtUtil;
import com.cg.springSecurity.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private Gson gson;
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //更新用户表上次登录时间、更新人、更新时间等字段
        User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (userDetails == null){
            //处理编码方式，防止中文乱码的情况
            httpServletResponse.setContentType("text/json;charset=utf-8");
            //塞到HttpServletResponse中返回给前台
            httpServletResponse.getWriter().write(gson.toJson(new ResultInfo<>("接受数据为空")));
        }else {
            //处理编码方式，防止中文乱码的情况
            httpServletResponse.setContentType("text/json;charset=utf-8");
            //塞到HttpServletResponse中返回给前台
            Map<String, String> data = new HashMap<>();
            String username = userDetails.getUsername();
            String token = jwtUtil.generate(username);
            data.put("username" , username);
            data.put("token", token);
            //将token的username保存到redis，实现服务端对用户的控制
            redisUtils.set(username, "token", jwtUtil.expiration, TimeUnit.HOURS);
            httpServletResponse.getWriter().write(gson.toJson(new ResultInfo<>(data)));
        }
        //此处还可以进行一些处理，比如登录成功之后可能需要返回给前台当前用户有哪些菜单权限，
        //进而前台动态的控制菜单的显示等，具体根据自己的业务需求进行扩展

        //返回json数据
//        String result = "登录成功" + userDetails.getUsername();

    }
}
